/*
 * @FileName: [RechargeableCardServiceImpl.java]
 * 
 * @Package com.bcinfo.iccard.service.impl
 * 
 * 
 * Copyright (c) 2011-2015 BCINFO Technology Limited Com.
 * All rights reserved.
 * 
 * This software is the confidential and proprietnewCardNums
 * information of BCINFO Technology Limited Company
 * ("Confidential Information"). You shall not disclose
 * such Confidential Information and shall use it only
 * in accordance with the terms of the contract agreement
 * you entered into with RKY.
 * 
 * $Rev: 1022 $
 * $LastChangedDate$
 * $LastChangedBy: xusp $
 * 
 * @category ICCARD
 * 
 * @version 1.1
 * 
 * @author $Author: xusp $
 * 
 * Change History:[Formatter: author date description] <br/>
 * 1
 * 2
 * 3
 */

package com.bcinfo.iccard.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.bcinfo.iccard.constant.ExpensiveRecordConstant;
import com.bcinfo.iccard.constant.RechargeableConstant;
import com.bcinfo.iccard.dao.ExpenseRecordMapper;
import com.bcinfo.iccard.dao.RechargeableCardCreditDetailMapper;
import com.bcinfo.iccard.dao.RechargeableCardMapper;
import com.bcinfo.iccard.dao.RechargeableCardStatusMapper;
import com.bcinfo.iccard.exception.CardNumIsExistException;
import com.bcinfo.iccard.exception.IccardDatabaseException;
import com.bcinfo.iccard.exception.IccardException;
import com.bcinfo.iccard.exception.InvalidParametersException;
import com.bcinfo.iccard.exception.RechargeableCardCancelPwdErrorException;
import com.bcinfo.iccard.exception.RechargeableCardCancelPwdNullException;
import com.bcinfo.iccard.exception.RechargeableCardIsNotExistByCardnumException;
import com.bcinfo.iccard.exception.RechargeableCardIsNotExistException;
import com.bcinfo.iccard.exception.RechargeableCardRechargeMoneyLessThanZeroException;
import com.bcinfo.iccard.exception.RechargeableCardRechargeMoneyNullException;
import com.bcinfo.iccard.exception.RechargeableCardRechargeTypeErrorException;
import com.bcinfo.iccard.exception.RechargeableCardStatusActivateException;
import com.bcinfo.iccard.exception.RechargeableCardStatusIsNotActivateException;
import com.bcinfo.iccard.exception.RechargeableCardUseNewPwdException;
import com.bcinfo.iccard.model.ExpenseRecord;
import com.bcinfo.iccard.model.RechargeableCard;
import com.bcinfo.iccard.model.RechargeableCardCancelDetail;
import com.bcinfo.iccard.model.RechargeableCardCreditDetail;
import com.bcinfo.iccard.model.RechargeableCardInfo;
import com.bcinfo.iccard.model.RechargeableCardStatus;
import com.bcinfo.iccard.service.RechargeableCardService;
import com.bcinfo.iccard.util.AESCryptor;
import com.bcinfo.iccard.util.PaginationList;
import com.bcinfo.iccard.util.TimeUtils;
import com.bcinfo.upp.ac.model.Operator;
import com.bcinfo.upp.sys.model.SysParameter;

/**
 * 一句话描述 <br/>
 * <p>
 * Description:<br/>
 * <p>
 * TODO 详细描述
 * 
 * <p>
 * For Examples <br/>
 * 
 * <PRE>
 *      TODO 代码使用示例
 * </PRE>
 * <p>
 */
@Service("rechargeableCardService")
public class RechargeableCardServiceImpl implements RechargeableCardService
{

    private RechargeableCardMapper             _rechargeableCardMapper;

    private RechargeableCardStatusMapper       _rechargeableCardStatusMapper;

    private RechargeableCardCreditDetailMapper _rechargeableCardCreditDetailMapper;

    private ExpenseRecordMapper                _expenseRecordMapper;

    public ExpenseRecordMapper get_expenseRecordMapper()
    {
        return _expenseRecordMapper;
    }

    public void set_expenseRecordMapper(ExpenseRecordMapper _expenseRecordMapper)
    {
        this._expenseRecordMapper = _expenseRecordMapper;
    }

    public RechargeableCardCreditDetailMapper get_rechargeableCardCreditDetailMapper()
    {
        return _rechargeableCardCreditDetailMapper;
    }

    public void set_rechargeableCardCreditDetailMapper(
            RechargeableCardCreditDetailMapper _rechargeableCardCreditDetailMapper)
    {
        this._rechargeableCardCreditDetailMapper = _rechargeableCardCreditDetailMapper;
    }

    private SqlSessionTemplate batchSqlSession;

    /**
     * @return the _rechargeableCardMapper
     */
    public RechargeableCardMapper get_rechargeableCardMapper()
    {
        return _rechargeableCardMapper;
    }

    /**
     * @param _rechargeableCardMapper
     *            the _rechargeableCardMapper to set
     */
    public void set_rechargeableCardMapper(RechargeableCardMapper _rechargeableCardMapper)
    {
        this._rechargeableCardMapper = _rechargeableCardMapper;
    }

    /**
     * @return the _rechargeableCardStatusMapper
     */
    public RechargeableCardStatusMapper get_rechargeableCardStatusMapper()
    {
        return _rechargeableCardStatusMapper;
    }

    /**
     * @param _rechargeableCardStatusMapper
     *            the _rechargeableCardStatusMapper to set
     */
    public void set_rechargeableCardStatusMapper(RechargeableCardStatusMapper _rechargeableCardStatusMapper)
    {
        this._rechargeableCardStatusMapper = _rechargeableCardStatusMapper;
    }

    /**
     * @return the batchSqlSession
     */
    public SqlSessionTemplate getBatchSqlSession()
    {
        return batchSqlSession;
    }

    /**
     * @param batchSqlSession
     *            the batchSqlSession to set
     */
    public void setBatchSqlSession(SqlSessionTemplate batchSqlSession)
    {
        this.batchSqlSession = batchSqlSession;
    }

    private static final Logger _logger = Logger.getLogger(RechargeableCardServiceImpl.class);

    /*
     * (non-Javadoc)
     * Description: <br/>
     * 
     * @param cardNum
     * 
     * @return
     * 
     * @throws IcCardDatabaseException
     * 
     * @see com.bcinfo.iccard.service.RechargeableCardService#add(java.lang.String)
     */
    @Override
    public int add(RechargeableCard rechargeableCard, long opId) throws IccardDatabaseException,
            CardNumIsExistException
    {
        if (_logger.isDebugEnabled())
        {
            _logger.debug("rechargeableCard=" + rechargeableCard.toString());
        }
        int count = 0;
        try
        {
            count = _rechargeableCardMapper.selectByCardNum(rechargeableCard.getRechargeableCardNum());
        }
        catch (DataAccessException e1)
        {
            _logger.error(ExceptionUtils.getStackTrace(e1));
            throw new IccardDatabaseException();
        }
        if (count > 0)
        {
            _logger.error("add:rechargeableCard=" + rechargeableCard + " is exist");
            throw new CardNumIsExistException();
        }
        int result = 0;
        try
        {
            result = _rechargeableCardMapper.insertSelective(rechargeableCard);
            if (result > 0)
            {
                RechargeableCardStatus rechargeableCardStatus = new RechargeableCardStatus();
                rechargeableCardStatus.setOp(opId);
                rechargeableCardStatus.setRechargeableCardId(rechargeableCard.getRechargeableCardId());
                rechargeableCardStatus.setRechargeableCardOpStatus((short) 0);
                _rechargeableCardStatusMapper.insertSelective(rechargeableCardStatus);
            }
        }
        catch (DataAccessException _e)
        {
            _logger.error(ExceptionUtils.getStackTrace(_e));
            throw new IccardDatabaseException();
        }
        return result;
    }

    /*
     * (non-Javadoc)
     * Description: <br/>
     * 
     * @param cardNums
     * 
     * @return
     * 
     * @throws IcCardDatabaseException
     * 
     * @see com.bcinfo.iccard.service.RechargeableCardService#batchAdd(java.lang.String[])
     */
    @Override
    public List<String> batchAdd(List<String> cardNums, long opId) throws IccardDatabaseException,
            InvalidParametersException
    {
        if (cardNums == null || cardNums.size() <= 0)
        {
            _logger.debug("batchAdd  parameter is wrong:cardNums=" + cardNums);
            throw new InvalidParametersException();
        }
        if (_logger.isDebugEnabled())
        {
            _logger.debug("batchAdd:cardNums=" + cardNums + ",opId=" + opId);
        }

        List<String> errorCardNums = _rechargeableCardMapper.selectByCardNums(cardNums);
        // List<String> errorCardNums = new ArrayList<String>();
        String regex = "\\w+";
        Pattern pattern = Pattern.compile(regex);
        List<String> list = new ArrayList<String>();
        for (String cardNum : cardNums)
        {
            Matcher matcher = pattern.matcher(cardNum);
            if (cardNum.length() == 19 && matcher.matches())
            {
                for (String errorCardNum : errorCardNums)
                {
                    if (cardNum.equals(errorCardNum))
                    {
                        list.add(cardNum);
                    }
                }
            }
            else
            {
                list.add(cardNum);
            }
        }
        cardNums.removeAll(list);
        SqlSession session = batchSqlSession.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        RechargeableCardMapper rechargeableCardMapper = session.getMapper(RechargeableCardMapper.class);
        RechargeableCardStatusMapper rechargeableCardStatusMapper = session
                .getMapper(RechargeableCardStatusMapper.class);
        List<RechargeableCard> lr = new ArrayList<RechargeableCard>();
        for (String cardNum : cardNums)
        {
            try
            {
                RechargeableCard rechargeableCard = new RechargeableCard();
                rechargeableCard.setRechargeableCardNum(cardNum);
                rechargeableCard.setRechargeableCardStatus((short) 0);
                rechargeableCard.setRechargeableCardType((short) 0);
                rechargeableCard.setRechargeableCardAccountTotal((float) 0);
                rechargeableCardMapper.insertSelective(rechargeableCard);
                lr.add(rechargeableCard);
            }
            catch (DataAccessException _e)
            {
                _logger.error(ExceptionUtils.getStackTrace(_e));
                throw new IccardDatabaseException();
            }
        }

        session.commit();
        for (RechargeableCard r : lr)
        {
            RechargeableCardStatus rechargeableCardStatus = new RechargeableCardStatus();
            rechargeableCardStatus.setOp(opId);
            rechargeableCardStatus.setRechargeableCardId(r.getRechargeableCardId());
            rechargeableCardStatus.setRechargeableCardOpStatus((short) 0);
            rechargeableCardStatusMapper.insertSelective(rechargeableCardStatus);
        }
        session.commit();
        session.clearCache();
        return list;
    }

    /*
     * (non-Javadoc)
     * Description: <br/>
     * 
     * @param status
     * 
     * @param pageSize
     * 
     * @param pageNo
     * 
     * @return
     * 
     * @throws IcCardDatabaseException
     * 
     * @throws InvalidParametersException
     * 
     * @see com.bcinfo.iccard.service.RechargeableCardService#find(int, int, int)
     */
    @Override
    public PaginationList<RechargeableCardInfo> find(String cardNum, int status, int pageSize, int pageNo)
            throws IccardDatabaseException, InvalidParametersException
    {
        PaginationList<RechargeableCardInfo> paginationList = new PaginationList<RechargeableCardInfo>();
        List<RechargeableCardInfo> rechargeableCards = null;
        int totalLogCount = 0;
        System.out.println("find:,status=" + status + ",cardNum=" + cardNum + ",pageSize=" + pageSize + ",pageNo="
                + pageNo);
        if (_logger.isDebugEnabled())
        {
            _logger.info("find:,status=" + status + ",cardNum=" + cardNum + ",pageSize=" + pageSize + ",pageNo="
                    + pageNo);
        }
        try
        {
            totalLogCount = _rechargeableCardMapper.selectCountByPage(cardNum, status);
        }
        catch (Exception e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
        if (pageNo <= 0 || totalLogCount < (pageNo - 1) * pageSize || pageSize <= 0)
        {
            _logger.error("parameter is wrong");
            throw new InvalidParametersException();
        }
        int benginIndex = pageSize * pageNo - pageSize;
        try
        {
            rechargeableCards = _rechargeableCardMapper.selectByPage(cardNum, status, benginIndex, pageSize);
        }
        catch (Exception e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }

        int totalPage = totalLogCount % pageSize == 0 ? totalLogCount / pageSize : totalLogCount / pageSize + 1;
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(rechargeableCards);
        paginationList.setTotalRecord(totalLogCount);
        return paginationList;
    }

    /*
     * (non-Javadoc)
     * Description: <br/>
     * 
     * @param cardNum
     * 
     * @param status
     * 
     * @return
     * 
     * @throws IccardDatabaseException
     * 
     * @throws InvalidParametersException
     * 
     * @see com.bcinfo.iccard.service.RechargeableCardService#findInList(java.lang.String, int)
     */
    @Override
    public List<RechargeableCard> findInList(String cardNum, int status) throws IccardDatabaseException,
            InvalidParametersException
    {
        List<RechargeableCard> rechargeableCards = null;
        if (_logger.isDebugEnabled())
        {
            _logger.info("find:,status=" + status + ",cardNum=" + cardNum);
        }
        try
        {
            rechargeableCards = _rechargeableCardMapper.selectByCaudNum(cardNum, status);
        }
        catch (Exception e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
        return rechargeableCards;
    }

    /*
     * (non-Javadoc)
     * Description: <br/>
     * 
     * @param cardNum
     * 
     * @param status
     * 
     * @return
     * 
     * @throws IccardDatabaseException
     * 
     * @throws InvalidParametersException
     * 
     * @see com.bcinfo.iccard.service.RechargeableCardService#findInList(java.lang.String, int)
     */
    @Override
    public List<Operator> findUserByRoleId(Long roleId) throws IccardDatabaseException
    {
        List<Operator> lo = null;
        if (_logger.isDebugEnabled())
        {
            _logger.info("findUserByRoleId:,roleId=" + roleId);
        }
        try
        {
            lo = _rechargeableCardMapper.selectUserByRoleId(roleId);
        }
        catch (Exception e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
        return lo;
    }

    /*
     * (non-Javadoc)
     * Description: <br/>
     * 
     * @param cardId
     * 
     * @return
     * 
     * @throws IcCardDatabaseException
     * 
     * @see com.bcinfo.iccard.service.RechargeableCardService#delete(long)
     */
    @Override
    public int delete(long cardId, long opId) throws IccardDatabaseException
    {
        int result = 0;
        if (_logger.isInfoEnabled())
        {
            _logger.info("delete:cardId=" + cardId);
        }
        try
        {
            result = _rechargeableCardMapper.deleteByPrimaryKey(cardId);

            if (result > 0)
            {
                _rechargeableCardStatusMapper.deleteByCardId(cardId);
            }
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
        return result;
    }

    /*
     * (non-Javadoc)
     * Description: <br/>
     * 
     * @param cardId
     * 
     * @return
     * 
     * @throws IcCardDatabaseException
     * 
     * @see com.bcinfo.iccard.service.RechargeableCardService#delete(long)
     */
    @Override
    public int batchDelete(long[] cardIds, long opId) throws IccardDatabaseException
    {
        int result = 0;
        if (_logger.isInfoEnabled())
        {
            _logger.info("batchDelete:cardIds=" + cardIds);
        }
        try
        {

            SqlSession session = batchSqlSession.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
            RechargeableCardMapper rechargeableCardMapper = session.getMapper(RechargeableCardMapper.class);
            RechargeableCardStatusMapper rechargeableCardStatusMapper = session
                    .getMapper(RechargeableCardStatusMapper.class);
            for (long cardId : cardIds)
            {
                System.out.println(cardId);
                rechargeableCardMapper.deleteByPrimaryKey(cardId);
                rechargeableCardStatusMapper.deleteByCardId(cardId);
            }
            session.commit();
            session.clearCache();
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
        return result;
    }

    /*
     * (non-Javadoc)
     * Description: <br/>
     * 
     * @param cardId
     * 
     * @param opId
     * 
     * @return
     * 
     * @throws IcCardDatabaseException
     * 
     * @see com.bcinfo.iccard.service.RechargeableCardService#outbound(long, long)
     */
    @Override
    public int outbound(RechargeableCard rechargeableCard, long opId, long receiverId) throws IccardDatabaseException,
            RechargeableCardIsNotExistException, InvalidParametersException
    {
        if (_logger.isInfoEnabled())
        {
            _logger.info("outbound:rechargeableCard=" + rechargeableCard.toString() + ",opId=" + opId);
        }
        if (rechargeableCard == null)
        {
            _logger.error("update parameter is wrong :crechargeableCard is null");
            throw new InvalidParametersException();
        }

        rechargeableCard.setRechargeableCardStatus((short) 1);
        try
        {
            int resultCount = _rechargeableCardMapper.updateByPrimaryKeySelective(rechargeableCard);

            if (resultCount > 0)
            {
                RechargeableCardStatus rechargeableCardStatus = new RechargeableCardStatus();
                rechargeableCardStatus.setOp(opId);
                rechargeableCardStatus.setRechargeableCardId(rechargeableCard.getRechargeableCardId());
                rechargeableCardStatus.setRechargeableCardOpStatus((short) 1);
                rechargeableCardStatus.setReceiverId(receiverId);
                _rechargeableCardStatusMapper.insertSelective(rechargeableCardStatus);
            }
            if (_logger.isDebugEnabled())
            {
                _logger.debug("outbound:result outbound count is " + resultCount);
            }
            return resultCount;
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
    }

    /*
     * (non-Javadoc)
     * Description: <br/>
     * 
     * @param cardId
     * 
     * @param opId
     * 
     * @return
     * 
     * @throws IcCardDatabaseException
     * 
     * @see com.bcinfo.iccard.service.RechargeableCardService#batchOutbound(long[], long)
     */
    @Override
    public int batchOutbound(long[] cardIds, long opId, long receiverId) throws IccardDatabaseException,
            InvalidParametersException
    {
        if (_logger.isInfoEnabled())
        {
            _logger.info("batchOutbound:cardIds=" + cardIds + ",opId=" + opId + "receiverId" + receiverId);
        }
        if (cardIds == null || cardIds.length == 0)
        {
            _logger.error("update parameter is wrong :lr size 0");
            throw new InvalidParametersException();
        }
        SqlSession session = batchSqlSession.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        RechargeableCardMapper rechargeableCardMapper = session.getMapper(RechargeableCardMapper.class);
        RechargeableCardStatusMapper rechargeableCardStatusMapper = session
                .getMapper(RechargeableCardStatusMapper.class);
        int resultCount = 0;
        for (long cardId : cardIds)
        {
            try
            {
                RechargeableCard rechargeableCard = new RechargeableCard();
                rechargeableCard.setRechargeableCardId(cardId);
                rechargeableCard.setRechargeableCardStatus((short) 1);
                resultCount = rechargeableCardMapper.updateByPrimaryKeySelective(rechargeableCard);

                // if (resultCount > 0){
                RechargeableCardStatus rechargeableCardStatus = new RechargeableCardStatus();
                rechargeableCardStatus.setOp(opId);
                rechargeableCardStatus.setRechargeableCardId(rechargeableCard.getRechargeableCardId());
                rechargeableCardStatus.setRechargeableCardOpStatus((short) 1);
                rechargeableCardStatus.setReceiverId(receiverId);
                rechargeableCardStatusMapper.insertSelective(rechargeableCardStatus);
                // }
            }
            catch (DataAccessException _e)
            {
                _logger.error(ExceptionUtils.getStackTrace(_e));
                throw new IccardDatabaseException();
            }
        }
        session.commit();
        session.clearCache();
        return resultCount;
    }

    @Override
    public PaginationList<RechargeableCardInfo> findByStatus(Long userId, String cardNum, Short status, int pageSize,
            int pageNo) throws IccardDatabaseException, InvalidParametersException
    {
        PaginationList<RechargeableCardInfo> paginationList = new PaginationList<RechargeableCardInfo>();
        List<RechargeableCardInfo> rechargeableCardInfo = null;
        int totalCount = 0;
        if (_logger.isDebugEnabled())
        {
            _logger.debug("findByStatus:status=" + status + ",pageSize=" + pageSize + ",pageNo=" + pageNo);
        }
        try
        {
            totalCount = _rechargeableCardMapper.selectCountByStatus(userId, cardNum, status);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
        if (pageNo <= 0 || totalCount < (pageNo - 1) * pageSize || pageSize <= 0)
        {
            _logger.error("parameter is wrong");
            throw new InvalidParametersException();
        }
        int benginIndex = pageSize * pageNo - pageSize;
        try
        {
            rechargeableCardInfo = _rechargeableCardMapper.selectPageByStatus(userId, cardNum, status, benginIndex,
                    pageSize);
        }
        catch (Exception e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }

        int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(rechargeableCardInfo);
        paginationList.setTotalRecord(totalCount);
        return paginationList;
    }

    @Override
    public int activate(long opId, String cardNum, Short rechargeType, float rechargeMoney, String pwd)
            throws RechargeableCardIsNotExistByCardnumException, RechargeableCardStatusActivateException,
            RechargeableCardRechargeMoneyNullException, RechargeableCardUseNewPwdException, IccardDatabaseException,
            RechargeableCardRechargeTypeErrorException

    {
        int result = 0;
        if (_logger.isDebugEnabled())
        {
            _logger.debug("activate:cardNum=" + cardNum + ",rechargeMoney=" + rechargeMoney);
        }
        if (!RechargeableConstant.RECHARGEABLE_DETAIL_RECHARGETYPE_MAP.containsKey(rechargeType))
        {
            _logger.equals("recharge:rechargeType is error");
            throw new RechargeableCardRechargeTypeErrorException();
        }

        // int count = _rechargeableCardMapper.selectByCardNum(cardNum);
        RechargeableCard rechargeableCard = _rechargeableCardMapper.selectCardByCardNum(cardNum);
        if (null == rechargeableCard)
        {
            _logger.error("activate:cardNum=" + cardNum + ",card is not exist");
            throw new RechargeableCardIsNotExistByCardnumException();
        }
        Short rechargeableCardStatus = rechargeableCard.getRechargeableCardStatus();
        String rechargeableCardPwd = rechargeableCard.getRechargeableCardPwd();
        // 为已激活状态，不允许再次被激活
        if (rechargeableCardStatus == RechargeableConstant.RECHARGEABLE_CARD_STATUS_ACTIVATE)
        {
            _logger.error("activate:cardNum =" + cardNum + ",is already activate");
            throw new RechargeableCardStatusActivateException();
        }
        Short rechargeableCardType = rechargeableCard.getRechargeableCardType();
        Long rechargeableCardId = rechargeableCard.getRechargeableCardId();
        rechargeableCard.setRechargeableCardNum(cardNum);
        rechargeableCard.setRechargeableCardStatus(RechargeableConstant.RECHARGEABLE_CARD_STATUS_ACTIVATE);
        // rechargeableCard.setRechargeableCardAccountTotal(rechargeMoney);
        rechargeableCard.setRechargeableCardValidTime(new TimeUtils().getNextYear4Timestamp());
        // 新卡
        if (rechargeableCardType == 0)
        {
            // rechargeableCardNew.setRechargeableCardType(RechargeableConstant.RECHARGEABLE_CARD_TYPE_NEW);
            // 输入金额大于或等于1000

            if (rechargeMoney >= 1000)
            {
                rechargeableCard.setRechargeableCardPwd(pwd);

            }
            else
            {
                // 1、界面不显示密码框。
                // 2、执行激活并充值操作。
                // 3、系统自动存入默认密码（默认密码在系统参数配置当中可以修改配置）。
                rechargeableCard.setRechargeableCardPwd(getDefaultPwdMd5());
            }
        }
        // 旧卡
        else if (rechargeableCardType == 1)
        {
            // 当过期被冻结的卡被要求重新激活的时候，填写充值金额为0时，需检测卡的余额，如余额为0时，
            // 要求输入充值金额才能重新激活，填写金额大于等于1000时，需检测用户的密码是否为系统默认密码。
            // 如果是，则需要提示要求用户设置密码，才能激活，否则不可激活。

            // 第一次激活时已使用非默认密码，第二次激活则无需输入密码

            Float accountTotal = rechargeableCard.getRechargeableCardAccountTotal();
            // 输入金额等于0，且余额为0
            if (accountTotal <= 0 && rechargeMoney <= 0)
            {

                _logger.error("activate:cardNum =" + cardNum + ",accounttotal is empty ,rechargeMoney must more than 0");
                throw new RechargeableCardRechargeMoneyNullException();
            }
            // 输入金额大于或等于1000，且用户使用的是系统默认密码
            if (rechargeMoney >= 1000)
            {
                if (rechargeableCardPwd.equals(getDefaultPwdMd5()))
                {
                    _logger.error("activate:cardNum =" + cardNum
                            + ",can not use default password ,please change another password");
                    throw new RechargeableCardUseNewPwdException();
                }
            }
        }
        // 激活入库操作，更新充值卡表，
        try
        {
            _rechargeableCardMapper.updateByPrimaryKeySelective(rechargeableCard);
        }
        catch (DataAccessException e)
        {
            _logger.error("activate:resultCount -data error");
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
        // 更新充值卡剩餘金額
        try
        {
            _rechargeableCardMapper.updateAccountTotalByCardId(rechargeableCardId, RechargeableConstant.ADD,
                    rechargeMoney);
        }
        catch (DataAccessException e)
        {
            _logger.error("activate:updateMoneyCount -data error");
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }

        // 充值卡明细表，
        RechargeableCardCreditDetail detail = new RechargeableCardCreditDetail();
        detail.setRechargeableCardId(rechargeableCardId);
        detail.setRechargeableCardCreditAmount(rechargeMoney);
        detail.setRechargeableCardCreditTime(new Timestamp(System.currentTimeMillis()));
        detail.setRechargeType(rechargeType);
        detail.setUserId(opId);
        detail.setIsAccountChecked(RechargeableConstant.RECHARGEABLE_DETAIL_ACCOUNT_CHECKED_NO);
        detail.setCheckAccountDate(null);
        detail.setOpStatus(RechargeableConstant.RECHARGEABLE_DETAIL_OPSTATUS_RECHARGE);
        try
        {

            _rechargeableCardCreditDetailMapper.insertSelective(detail);
        }
        catch (DataAccessException e)
        {
            _logger.error("activate:detailCount -data error");
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }

        // 充值卡状态变更表
        RechargeableCardStatus rechargeableCardStatusModel = new RechargeableCardStatus();
        rechargeableCardStatusModel.setOp(opId);
        rechargeableCardStatusModel.setRechargeableCardId(rechargeableCardId);
        rechargeableCardStatusModel.setRechargeableCardOpStatus(RechargeableConstant.RECHARGEABLE_CARD_STATUS_ACTIVATE);
        try
        {
            _rechargeableCardStatusMapper.insertSelective(rechargeableCardStatusModel);
        }
        catch (DataAccessException e)
        {
            _logger.error("activate:statusCount -data error");
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
        result = 1;

        return result;
    }

    @Override
    public int recharge(long opId, String cardNum, Short rechargeType, float rechargeMoney, String pwd)
            throws IccardDatabaseException, RechargeableCardRechargeMoneyLessThanZeroException,
            RechargeableCardIsNotExistByCardnumException, RechargeableCardStatusIsNotActivateException,
            RechargeableCardUseNewPwdException, RechargeableCardRechargeTypeErrorException
    {
        int result = 0;
        if (_logger.isDebugEnabled())
        {
            _logger.debug("recharge:userId= " + opId + ",cardNum=" + cardNum + ",rechargeType=" + rechargeType
                    + ",rechargeMoney=" + rechargeMoney);
        }
        if (rechargeMoney <= 0)
        {
            _logger.error("recharge:rechargeMoney can not less than zero");
            throw new RechargeableCardRechargeMoneyLessThanZeroException();
        }
        if (!RechargeableConstant.RECHARGEABLE_DETAIL_RECHARGETYPE_MAP.containsKey(rechargeType))
        {
            _logger.equals("recharge:rechargeType is error");
            throw new RechargeableCardRechargeTypeErrorException();
        }
        RechargeableCard rechargeableCard = _rechargeableCardMapper.selectCardByCardNum(cardNum);
        if (null == rechargeableCard)
        {
            _logger.error("activate:cardNum=" + cardNum + ",card is not exist");
            throw new RechargeableCardIsNotExistByCardnumException();
        }
        Short rechargeableCardStatus = rechargeableCard.getRechargeableCardStatus();
        Long rechargeableCardId = rechargeableCard.getRechargeableCardId();
        // 不是激活状态的卡，不能进行充值
        if (rechargeableCardStatus != RechargeableConstant.RECHARGEABLE_CARD_STATUS_ACTIVATE)
        {
            _logger.error("recharge:cardNum =" + cardNum + ",status is not activate,can not be recharge");
            throw new RechargeableCardStatusIsNotActivateException();
        }
        String rechargeableCardPwd = rechargeableCard.getRechargeableCardPwd();
        if (rechargeMoney >= 1000)
        {
            if (rechargeableCardPwd.equals(getDefaultPwdMd5()) && pwd.equals(rechargeableCardPwd))
            {
                _logger.error("recharge:cardNum =" + cardNum
                        + ",can not use default password ,please change another password");
                throw new RechargeableCardUseNewPwdException();
            }
            rechargeableCard.setRechargeableCardPwd(pwd);
        }
        // 更新充值卡表，
        int resultCount = _rechargeableCardMapper.updateByPrimaryKeySelective(rechargeableCard);
        if (resultCount < 1)
        {
            _logger.error("recharge:resultCount -data error");
            throw new IccardDatabaseException();
        }
        // 更新充值卡剩餘金額
        int updateMoneyCount = _rechargeableCardMapper.updateAccountTotalByCardId(rechargeableCardId,
                RechargeableConstant.ADD, rechargeMoney);

        if (updateMoneyCount < 1)
        {
            _logger.error("recharge:updateMoneyCount -data error");
            throw new IccardDatabaseException();
        }

        // 充值卡明细表，
        RechargeableCardCreditDetail detail = new RechargeableCardCreditDetail();
        detail.setRechargeableCardId(rechargeableCardId);
        detail.setRechargeableCardCreditAmount(rechargeMoney);
        detail.setRechargeableCardCreditTime(new Timestamp(System.currentTimeMillis()));
        detail.setRechargeType(rechargeType);
        detail.setUserId(opId);
        detail.setIsAccountChecked(RechargeableConstant.RECHARGEABLE_DETAIL_ACCOUNT_CHECKED_NO);
        detail.setCheckAccountDate(null);
        try
        {
            _rechargeableCardCreditDetailMapper.insertSelective(detail);
        }
        catch (DataAccessException e)
        {
            _logger.error("recharge:detailCount -data error");
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }

        // 充值卡状态变更表
        RechargeableCardStatus rechargeableCardStatusModel = new RechargeableCardStatus();
        rechargeableCardStatusModel.setOp(opId);
        rechargeableCardStatusModel.setRechargeableCardId(rechargeableCardId);
        rechargeableCardStatusModel.setRechargeableCardOpStatus(RechargeableConstant.RECHARGEABLE_CARD_STATUS_ACTIVATE);
        try
        {
            _rechargeableCardStatusMapper.insertSelective(rechargeableCardStatusModel);
        }
        catch (DataAccessException e)
        {
            _logger.error("activate:statusCount -data error");
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
        result = 1;
        return result;
    }

    @Override
    public PaginationList<RechargeableCardInfo> findDetails(Long userId, String cardNum, String beginTime,
            String endTime, int pageSize, int pageNo) throws IccardDatabaseException, InvalidParametersException
    {
        if (_logger.isDebugEnabled())
        {
            _logger.debug("findDetails:userId= " + userId + ",cardNum=" + cardNum + ",beginTime=" + beginTime
                    + ",endTime=" + endTime);
        }

        PaginationList<RechargeableCardInfo> paginationList = new PaginationList<RechargeableCardInfo>();
        List<RechargeableCardInfo> rechargeableCardInfoList = null;
        int totalCount = 0;
        try
        {
            totalCount = _rechargeableCardMapper.selectDetailCountByCardNum(userId, cardNum, beginTime, endTime);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
        if (pageNo <= 0 || totalCount < (pageNo - 1) * pageSize || pageSize <= 0)
        {
            _logger.error("parameter is wrong");
            throw new InvalidParametersException();
        }
        int benginIndex = pageSize * pageNo - pageSize;
        try
        {
            rechargeableCardInfoList = _rechargeableCardMapper.selectDetailPageByCardNum(userId, cardNum, beginTime,
                    endTime, benginIndex, pageSize);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }

        int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(rechargeableCardInfoList);
        paginationList.setTotalRecord(totalCount);
        return paginationList;
    }

    @Deprecated
    @Override
    public RechargeableCardInfo canceledCardInfo(String cardNum, String pwd)
            throws RechargeableCardCancelPwdNullException, RechargeableCardCancelPwdErrorException,
            RechargeableCardIsNotExistException, IccardDatabaseException
    {
        List<RechargeableCardInfo> list = null;
        RechargeableCardInfo info = null;
        if (_logger.isDebugEnabled())
        {
            _logger.debug("canceledCardInfo:cardNum" + cardNum);
        }
        try
        {
            if (org.apache.commons.lang3.StringUtils.isBlank(pwd))
            {
                _logger.error("canceledCardInfo:cardNum=" + cardNum + ",pwd is null");
                throw new RechargeableCardCancelPwdNullException();
            }
            list = _rechargeableCardMapper.selectPageByStatus(null, cardNum,
                    RechargeableConstant.RECHARGEABLE_VALUE_ALL, 0, 1);
            if (null == list || list.isEmpty())
            {
                _logger.error("canceledCardInfo:cardNum=" + cardNum + ",result is null");
                throw new RechargeableCardIsNotExistException();
            }
            info = list.get(0);
            String rechargeableCardPwd = info.getRechargeableCardPwd();
            // 校验密码
            if (!rechargeableCardPwd.equals(pwd))
            {
                _logger.error("canceledCardInfo:cardNum=" + cardNum + ",pwd error");
                throw new RechargeableCardCancelPwdErrorException();
            }
        }
        catch (Exception e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }

        return info;
    }

    @Override
    public int cancellation(RechargeableCardInfo info, Long opId) throws IccardDatabaseException,
            RechargeableCardIsNotExistException, RechargeableCardCancelPwdNullException
    {
        if (null == info)
        {
            _logger.error("cancellation:card is not exist");
            throw new RechargeableCardIsNotExistException();
        }
        String pwd = info.getRechargeableCardPwd();
        String cardNum = info.getRechargeableCardNum();
        Long cardId = info.getRechargeableCardId();
        Float accountTotal = info.getRechargeableCardAccountTotal();

        if (_logger.isDebugEnabled())
        {
            _logger.debug("cancellation:cardNum" + cardNum);
        }

        if (org.apache.commons.lang3.StringUtils.isBlank(pwd))
        {
            _logger.error("cancellation:cardNum=" + cardNum + ",pwd is null");
            throw new RechargeableCardCancelPwdNullException();
        }
        // Map<String, Object> params = new HashMap<String, Object>();
        // params.put("channelIds", channelIds);
        // params.put("keyword", keyword);

        // 修改充值卡信息
        RechargeableCard card = new RechargeableCard();
        card.setRechargeableCardId(cardId);
        card.setRechargeableCardStatus(RechargeableConstant.RECHARGEABLE_CARD_STATUS_CANCEL);
        card.setRechargeableCardType(RechargeableConstant.RECHARGEABLE_CARD_TYPE_OLD);
        card.setRechargeableCardAccountTotal(RechargeableConstant.RECHARGEABLE_TOTAL_ACCOUNT_ZERO);
        card.setRechargeableCardValidTime(null);
        card.setRechargeableCardPwd(getDefaultPwdMd5());
        try
        {
            _rechargeableCardMapper.updateByPrimaryKeySelective(card);
        }
        catch (DataAccessException e)
        {
            _logger.error("cancellation:rechargecard -data error");
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }

        // 充值卡状态变更表
        RechargeableCardStatus rechargeableCardStatusModel = new RechargeableCardStatus();
        rechargeableCardStatusModel.setRechargeableCardId(cardId);
        rechargeableCardStatusModel.setOp(opId);
        rechargeableCardStatusModel.setOpDate(new Timestamp(System.currentTimeMillis()));
        rechargeableCardStatusModel.setRechargeableCardOpStatus(RechargeableConstant.RECHARGEABLE_CARD_STATUS_CANCEL);
        try
        {
            _rechargeableCardStatusMapper.insertSelective(rechargeableCardStatusModel);
        }
        catch (DataAccessException e)
        {
            _logger.error("cancellation:statusCount -data error");
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }

        // 充值卡明细表，
        RechargeableCardCreditDetail detail = new RechargeableCardCreditDetail();
        detail.setRechargeableCardId(cardId);
        detail.setRechargeableCardCreditAmount(-accountTotal);
        detail.setRechargeableCardCreditTime(new Timestamp(System.currentTimeMillis()));
        detail.setRechargeType(RechargeableConstant.RECHARGEABLE_DETAIL_RECHARGETYPE_CASH);
        detail.setUserId(opId);
        detail.setIsAccountChecked(RechargeableConstant.RECHARGEABLE_DETAIL_ACCOUNT_CHECKED_NO);
        detail.setCheckAccountDate(null);
        detail.setOpStatus(RechargeableConstant.RECHARGEABLE_DETAIL_OPSTATUS_REFUND);
        try
        {
            _rechargeableCardCreditDetailMapper.insertSelective(detail);
        }
        catch (DataAccessException e)
        {
            _logger.error("cancellation:detailCount -data error");
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }

        return 1;
    }

    @Override
    public PaginationList<RechargeableCardCreditDetail> findCanceledSumByDay(String beginTime, String endTime,
            int pageSize, int pageNo) throws IccardDatabaseException, InvalidParametersException
    {
        if (_logger.isDebugEnabled())
        {
            _logger.debug("findCanceledSumByDay:beginTime=" + beginTime + ",endTime=" + endTime + ",status="
                    + RechargeableConstant.RECHARGEABLE_DETAIL_OPSTATUS_REFUND);
        }

        PaginationList<RechargeableCardCreditDetail> paginationList = new PaginationList<RechargeableCardCreditDetail>();
        List<RechargeableCardCreditDetail> rechargeableCardInfoList = null;
        int totalCount = 0;
        try
        {
            totalCount = _rechargeableCardCreditDetailMapper.selectSumCountByDayAndStatus(beginTime, endTime,
                    RechargeableConstant.RECHARGEABLE_DETAIL_OPSTATUS_REFUND);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
        if (pageNo <= 0 || totalCount < (pageNo - 1) * pageSize || pageSize <= 0)
        {
            _logger.error("parameter is wrong");
            throw new InvalidParametersException();
        }
        int benginIndex = pageSize * pageNo - pageSize;
        try
        {
            rechargeableCardInfoList = _rechargeableCardCreditDetailMapper.selectSumByDayAndStatus(beginTime, endTime,
                    benginIndex, pageSize, RechargeableConstant.RECHARGEABLE_DETAIL_OPSTATUS_REFUND);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }

        int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(rechargeableCardInfoList);
        paginationList.setTotalRecord(totalCount);
        return paginationList;
    }

    @Override
    public PaginationList<RechargeableCardCancelDetail> findCanceledDetailsList(String cardNum, Long userId,
            String beginTime, String endTime, int pageSize, int pageNo) throws IccardDatabaseException,
            InvalidParametersException
    {
        if (_logger.isDebugEnabled())
        {
            _logger.debug("findCanceledDetails:cardNum=" + cardNum + ",userId=" + userId + ",beginTime=" + beginTime
                    + ",endTime=" + endTime + ",pageSize=" + pageSize + ",pageNo=" + pageNo + ",status="
                    + RechargeableConstant.RECHARGEABLE_DETAIL_OPSTATUS_REFUND);
        }

        PaginationList<RechargeableCardCancelDetail> paginationList = new PaginationList<RechargeableCardCancelDetail>();
        List<RechargeableCardCancelDetail> rechargeableCardInfoList = null;
        int totalCount = 0;
        try
        {
            totalCount = _rechargeableCardCreditDetailMapper.selectCancelCount(cardNum, userId, beginTime, endTime);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
        if (pageNo <= 0 || totalCount < (pageNo - 1) * pageSize || pageSize <= 0)
        {
            _logger.error("parameter is wrong");
            throw new InvalidParametersException();
        }
        int benginIndex = pageSize * pageNo - pageSize;
        try
        {
            rechargeableCardInfoList = _rechargeableCardCreditDetailMapper.selectCancelDetailsList(cardNum, userId,
                    beginTime, endTime, benginIndex, pageSize);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
        int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(rechargeableCardInfoList);
        paginationList.setTotalRecord(totalCount);
        return paginationList;
    }

    @Override
    public RechargeableCardInfo findByCardnum(String cardNum, String pwd)
            throws RechargeableCardCancelPwdNullException, RechargeableCardIsNotExistException,
            RechargeableCardCancelPwdErrorException, IccardDatabaseException
    {
        List<RechargeableCardInfo> list = null;
        RechargeableCardInfo info = null;
        if (_logger.isDebugEnabled())
        {
            _logger.debug("canceledCardInfo:cardNum" + cardNum);
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(pwd))
        {
            _logger.error("canceledCardInfo:cardNum=" + cardNum + ",pwd is null");
            throw new RechargeableCardCancelPwdNullException();
        }
        try
        {
            list = _rechargeableCardMapper.selectPageByStatus(null, cardNum,
                    RechargeableConstant.RECHARGEABLE_VALUE_ALL, 0, 1);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
        if (null == list || list.isEmpty())
        {
            _logger.error("canceledCardInfo:cardNum=" + cardNum + ",result is null");
            throw new RechargeableCardIsNotExistException();
        }
        info = list.get(0);
        String rechargeableCardPwd = info.getRechargeableCardPwd();
        // 校验密码
        try
        {
            if (!rechargeableCardPwd.equals(pwd))
            {
                _logger.error("canceledCardInfo:cardNum=" + cardNum + ",pwd error");
                throw new RechargeableCardCancelPwdErrorException();
            }
        }
        catch (IccardException e)
        {
            e.printStackTrace();
        }

        return info;
    }

    @Override
    public PaginationList<ExpenseRecord> findConsumeRecords(String cardNum, String merchantName, String beginTime,
            String endTime, int pageSize, int pageNo) throws IccardDatabaseException, InvalidParametersException
    {

        if (_logger.isDebugEnabled())
        {
            _logger.debug("findConsumeRecords:cardNum=" + cardNum + ",merchantName =" + merchantName + "beginTime="
                    + beginTime + ",endTime=" + endTime + ",pageSize=" + pageSize + ",pageNo=" + pageNo);
        }

        PaginationList<ExpenseRecord> paginationList = new PaginationList<ExpenseRecord>();
        List<ExpenseRecord> rechargeableCardInfoList = null;
        int totalCount = 0;
        try
        {
            totalCount = _expenseRecordMapper.selectCountByCardNum(cardNum, merchantName,
                    ExpensiveRecordConstant.EXPENSIVERECORD_STATUS_CONSUME,
                    ExpensiveRecordConstant.EXPENSIVERECORD_ISACCOUNT_ALL,
                    ExpensiveRecordConstant.EXPENSIVERECORD_CARDTYPE_RECHARGE, beginTime, endTime);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
        if (pageNo <= 0 || totalCount < (pageNo - 1) * pageSize || pageSize <= 0)
        {
            _logger.error("parameter is wrong");
            throw new InvalidParametersException();
        }
        int benginIndex = pageSize * pageNo - pageSize;
        try
        {
            rechargeableCardInfoList = _expenseRecordMapper.selectPageByCardNum(cardNum, merchantName,
                    ExpensiveRecordConstant.EXPENSIVERECORD_STATUS_CONSUME,
                    ExpensiveRecordConstant.EXPENSIVERECORD_ISACCOUNT_ALL,
                    ExpensiveRecordConstant.EXPENSIVERECORD_CARDTYPE_RECHARGE, beginTime, endTime, benginIndex,
                    pageSize);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }

        int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(rechargeableCardInfoList);
        paginationList.setTotalRecord(totalCount);
        return paginationList;
    }

    @Override
    public PaginationList<RechargeableCardInfo> findRechargeRecords(String cardNum, Short rechargeType,
            String beginTime, String endTime, int pageSize, int pageNo) throws IccardDatabaseException,
            InvalidParametersException
    {
        if (_logger.isDebugEnabled())
        {
            _logger.debug("findRechargeRecords:cardNum=" + cardNum + ",rechargeType =" + rechargeType + "beginTime="
                    + beginTime + ",endTime=" + endTime + ",pageSize=" + pageSize + ",pageNo=" + pageNo);
        }

        PaginationList<RechargeableCardInfo> paginationList = new PaginationList<RechargeableCardInfo>();
        List<RechargeableCardInfo> rechargeableCardInfoList = null;
        int totalCount = 0;
        try
        {
            totalCount = _rechargeableCardMapper.selectDetailCountByCardNumAndRechargeType(cardNum, rechargeType,
                    beginTime, endTime);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }
        if (pageNo <= 0 || totalCount < (pageNo - 1) * pageSize || pageSize <= 0)
        {
            _logger.error("parameter is wrong");
            throw new InvalidParametersException();
        }
        int benginIndex = pageSize * pageNo - pageSize;
        try
        {
            rechargeableCardInfoList = _rechargeableCardMapper.selectDetailPageByCardNumAndRechargeType(cardNum,
                    rechargeType, beginTime, endTime, benginIndex, pageSize);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new IccardDatabaseException();
        }

        int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(rechargeableCardInfoList);
        paginationList.setTotalRecord(totalCount);
        return paginationList;
    }

    /*
     * (non-Javadoc)
     * Description: <br/>
     * 
     * @param cardNum
     * 
     * @return
     * 
     * @throws IccardDatabaseException
     * 
     * @see com.bcinfo.iccard.service.RechargeableCardService#load(java.lang.String)
     */
    @Override
    public RechargeableCard load(String cardNum) throws IccardDatabaseException
    {
        if (_logger.isDebugEnabled())
        {
            _logger.debug("load:cardNum=" + cardNum);
        }
        try
        {
            RechargeableCard card = _rechargeableCardMapper.load(cardNum);
            return card;
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    @Override
    public List<Operator> selectUserByRoleIdAndUserName(String keyword, int maxRows)
    {
        List<Operator> list = null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(keyword))
        {
            list = _rechargeableCardMapper.selectUserByRoleIdAndUserName(keyword, maxRows);
        }
        return list;
    }

    @Override
    public RechargeableCard findByCardNum(String cardNum) throws IccardDatabaseException,
            RechargeableCardIsNotExistByCardnumException
    {
        if (_logger.isDebugEnabled())
        {
            _logger.debug("load:cardNum=" + cardNum);
        }
        try
        {
            RechargeableCard card = _rechargeableCardMapper.load(cardNum);
            if (null == card)
            {
                _logger.error("findByCardNum:cardNum=" + cardNum + ",is not exist");
                throw new RechargeableCardIsNotExistByCardnumException();
            }
            return card;
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    public String getConfigByKey(String key)
    {
        String value = null;
        if (_logger.isInfoEnabled())
        {
            _logger.info("getConfigByKey:key=" + key);
        }
        try
        {
            List<SysParameter> list = _rechargeableCardMapper.selectByKey(key);
            if ((list != null) && (list.size() > 0))
            {
                value = ((SysParameter) list.get(0)).getValue();
                if (_logger.isDebugEnabled())
                {
                    _logger.debug("key=" + key + ",value=" + value);
                }
            }
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
        }
        return value;
    }

    public String getDefaultPwdMd5()
    {
        String defaultPwd = getConfigByKey(RechargeableConstant.SysConfigValue_Key);
        if (StringUtils.isBlank(defaultPwd))
        {
            defaultPwd = "pwd";
        }
        String md5Pwd = "";
        try
        {
            md5Pwd = AESCryptor.encrypt(defaultPwd);
        }
        catch (IccardException e)
        {
            e.printStackTrace();
        }
        return md5Pwd;
    }

    @Override
    public float findCancelSum(String beginTime, String endTime)
    {
        float amount = _rechargeableCardCreditDetailMapper.selectCancelSum(beginTime, endTime);
        return amount;
    }
}
